<template>
  <div
    :class="{
      'lc-fixed-toolbar':checkMode
    }"
    class="data-template-list lc-fixed-top">
    <van-nav-bar
      :title="generateTitle(title)"
      :left-text="$t('back')"
      :right-text="rightText"
      left-arrow
      fixed
      @click-left="onClickLeft"
      @click-right="toCheckMode()"/>

    <van-search
      v-show="$utils.isNotEmpty(queryKey)"
      v-model="search"
      @search="onSearch"
    />
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        @load="onLoad">
        <van-swipe-cell
          v-for="(item,index) in list"
          :key="item[idKey]+index"
          :right-width="removeButton?65:0"
          :on-close="onClose">
          <card-list
            :avatar="false"
            :check-mode="checkMode"
            :checked="checkedIds.includes(item[idKey])"
            @click="onClick(item)">
            <!--标题-->
            <field-formatter
              slot="title"
              :label-key="labelField['name']"
              :data="item"
              :template-fields="templateFields"
            />
            <!--描述展示-->
            <div
              v-if="descField&&descField['name']&&item[descField['name']]"
              slot="desc"
              class="van-card-list__desc">
              <span class="van-card-list__desc__title">{{ descField['label'] }}:</span>
              <field-formatter
                :label-key="descField['name']"
                :data="item"
                :template-fields="templateFields"
                default-value=""
              />
            </div>

          </card-list>
          <span
            v-if="removeButton"
            slot="right"
            @click="removeData(item)" >{{ $t('delete') }}</span>
        </van-swipe-cell>
      </van-list>
      <list-result-page
        :result-type="resultType"
        :error-type="errorType"
        :result-message="resultMessage"/>
    </van-pull-refresh>
    <!--添加按钮-->
    <div
      v-if="addButton"
      v-show="!checkMode"
      class="palette-button">
      <lc-palette-button
        content="+"
        direction="lt"
        main-button-style="color:#fff;background-color:#26a2ff;"
        @click="onClickRight" />
    </div>
    <!--工具栏 -->
    <lc-toolbar
      v-show="checkMode"
      :actions="actions"/>
  </div>
</template>
<script>
import { queryDataJson, removeFormData } from '@/api/platform/data/dataTemplate'
import { loadDataTemplateById, getDataTemplateListTemplate, buildDataTemplateFields } from '@/utils/data/template'
import { transformToTreeFormat } from '@/utils/tree'
import { formatParams, loadFinished, getResultType } from '@/utils/params'
import i18n from '@/utils/i18n'
import CardList from '@/components/CardList'
import ListResultPage from '@/components/ListResultPage'
import LcPaletteButton from '@/components/PaletteButton'
import LcToolbar from '@/components/LcToolbar'
import FieldFormatter from '@/components/DataTemplate/field-formatter'

export default {
  name: 'TemplateList',
  components: {
    CardList,
    ListResultPage,
    LcPaletteButton,
    LcToolbar,
    FieldFormatter
  },

  data() {
    return {
      search: '',
      title: '',
      list: [],
      page: 1,
      loading: false,
      finished: false,
      isLoading: true,
      resultType: 'init',
      errorType: null,
      resultMessage: null,

      idKey: '',
      labelField: '',
      descField: '',

      queryKey: '',
      isTree: false,
      templateId: '',
      templateKey: '',
      formKey: '',

      templateFields: {}, // 模版字段

      editButtons: '', // 编辑按钮
      functionButtons: [], // 功能按钮

      checkMode: false,
      checkedIds: [],
      actions: []
    }
  },
  computed: {
    addButton() {
      return this.includesFunctionButton('add')
    },
    removeButton() {
      return this.includesFunctionButton('remove')
    },
    editButton() {
      return this.includesFunctionButton('edit')
    },
    rightText() {
      if (this.list.length > 0) {
        return this.checkMode ? this.$t('common.button.cancel') : this.$t('common.button.manage')
      }
      return null
    }
  },
  created() {
    const params = this.$route.params
    this.templateId = params.id
    this.loadDataTemplate(this.templateId)
  },
  methods: {
    loadDataTemplate(id) {
      const params = {}
      loadDataTemplateById(id, params).then((data) => {
        this.title = data['name']
        i18n.setTitle(this.title)
        const template = getDataTemplateListTemplate(data)
        this.templateFields = buildDataTemplateFields(data.fields)
        this.buildKey(data, template)
        this.loadData()
      }).catch((e) => {
        console.error(e)
      // TODO 异常
      })
    },
    buildKey(dataTemplate, template) {
      this.idKey = dataTemplate['unique']
      this.templateKey = dataTemplate['key']
      this.formKey = dataTemplate['attrs']['form_key']
      this.queryKey = this.getQueryKey(template['query_columns'])
      if (dataTemplate.showType === 'tree') {
        this.isTree = true
        const displayColumns = template['display_columns']
        if (this.$utils.isNotEmpty(displayColumns)) {
          this.labelField = displayColumns['name_key']
          this.idKey = displayColumns['id_key']
          this.parentIdKey = displayColumns['pid_key']
        }
      } else if (dataTemplate.showType === 'list') {
        this.isTree = false
        const displayColumns = template['display_columns']
        if (this.$utils.isNotEmpty(displayColumns)) {
          this.labelField = displayColumns[0] || {}
          this.descField = displayColumns[1] || {}
        }
        this.editButtons = template['buttons']['edit_buttons']
        this.functionButtons = template['buttons']['function_buttons']
        this.initToolbarAction()
      }
    },
    onSearch() {
      this.resultType = 'init'
      this.page = 1
      this.list = []
      this.loadData()
    },
    onLoad() {
      this.loadData()
    },
    loadData() {
      if (this.$utils.isEmpty(this.templateKey)) {
        return
      }
      const params = {
        key: this.templateKey,
        dynamicParams: '', // 动态参数,获取页面的值
        filterConditionKey: '' // 多个过滤条件
      }
      if (this.search && this.queryKey) {
        params[`Q^${this.queryKey}^SL`] = this.search
      }
      // 加载数据
      queryDataJson(formatParams(params, this.page)).then(response => {
        const dataResult = response.data.dataResult

        if (this.$utils.isNotEmpty(dataResult)) {
          if (this.isTree) {
            this.list = transformToTreeFormat(dataResult, {
              idKey: this.idKey,
              parentIdKey: this.parentIdKey,
              childrenKey: this.childrenKey
            })
            // 初始化最顶级数据
            this.initRootTreeData(response.vars)
          } else {
            this.page++
            this.list = this.list.concat(dataResult)
            this.finished = false
          }
        }

        if (this.isTree) {
          this.finished = true
        } else {
          if (loadFinished(response.data.pageResult)) {
            this.finished = true
          }
        }

        this.loading = false
        this.isLoading = false
        // 结果类型
        this.resultType = getResultType(this.list, this.finished)
      }).catch((e) => {
        this.loading = false
        this.isLoading = false
        this.finished = true
        this.resultType = 'error'
        this.resultMessage = e.message
      })
    },
    onRefresh() {
      this.resultType = 'init'
      this.isLoading = true
      this.page = 1
      this.list = []
      this.loadData()
    },
    onClick(item) {
      if (this.checkMode) {
        const index = this.checkedIds.indexOf(item[this.idKey])
        if (index > -1) {
          this.checkedIds.splice(index, 1)
        } else {
          this.checkedIds.push(item[this.idKey])
        }
      } else {
        this.gotoForm({
          isEdit: false,
          pk: item[this.idKey]
        })
      }
    },

    generateTitle(name, title) { // generateTitle by vue-i18n
      return i18n.generateTitle(name, title)
    },
    gotoForm({ pk = '', isEdit = true }) {
      this.$router.push({
        name: 'dataTemplateform',
        query: {
          templateKey: this.templateKey,
          templateId: this.templateId,
          formKey: this.formKey,
          pk: pk,
          isEdit: isEdit
        },
        params: {
          buttons: isEdit ? this.editButtons : []
        }
      })
    },
    onClickLeft() {
      this.$router.push({ name: 'dashboard' })
    },
    onClickRight() {
      this.gotoForm({})
    },
    onClose(clickPosition, instance) {
      switch (clickPosition) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close()
          break
        case 'right':
          instance.open()
          break
      }
    },
    editData(isEdit) {
      if (this.checkedIds.length === 0) {
        return this.$toast(this.$t('common.dialog.selectedRecords'))
      }
      if (this.checkedIds.length > 1) {
        return this.$toast(this.$t('common.dialog.multipleSelected'))
      }
      this.gotoForm({
        isEdit: this.$utils.isEmpty(isEdit) ? true : isEdit,
        pk: this.checkedIds[0]
      })
    },
    detailData(item) {
      if (this.checkMode) {
        this.editData(false)
      } else {
        this.gotoForm({
          isEdit: false,
          pk: item[this.idKey]
        })
      }
    },
    removeDatas() {
      if (this.checkedIds.length === 0) {
        return this.$toast(this.$t('common.dialog.selectedRecords'))
      }
      this.removeRecord(this.checkedIds.join(','), (r) => {
        this.checkMode = false
        this.checkedIds = []
      })
    },
    removeData(item) {
      this.removeRecord(item[this.idKey])
    },
    removeRecord(ids, callback) {
      this.$dialog.confirm({
        title: '提示',
        message: '确定删除？'
      }).then(() => {
        removeFormData({
          id: ids,
          idKey: this.idKey,
          formKey: this.formKey
        }).then(() => {
          this.$toast.success('删除成功！')
          this.onRefresh()
          if (callback) { callback(true) }
        })
      })
    },
    toCheckMode() {
      if (this.checkMode) {
        this.show = true
      }
      this.checkMode = !this.checkMode
    },
    initToolbarAction() {
      const functionButtons = this.functionButtons
      for (let i = 0; i < functionButtons.length; i++) {
        const action = {}
        if (functionButtons[i].button_type === 'remove') {
          action['name'] = functionButtons[i].label
          action['buttonType'] = 'danger'
          action['callback'] = this.removeDatas
        } else if (functionButtons[i].button_type === 'edit') {
          action['name'] = functionButtons[i].label
          action['buttonType'] = 'primary'
          action['callback'] = this.editData
        } else if (functionButtons[i].button_type === 'detail') {
          action['name'] = functionButtons[i].label
          action['buttonType'] = 'default'
          action['callback'] = this.detailData
        }
        if (this.$utils.isNotEmpty(action)) {
          this.actions.push(action)
        }
      }
    },
    includesFunctionButton(key) {
      const btns = this.functionButtons.map((button) => {
        return button['button_type']
      })
      return btns.includes(key)
    },
    getQueryKey(queryColumns) {
      if (this.$utils.isNotEmpty(queryColumns) && queryColumns[0]) {
        return queryColumns[0].name
      }
    }
  }

}
</script>
<style lang="scss">
  .data-template-list{
    .van-swipe-cell__left{
      color: #FFFFFF;
      font-size: 15px;
      width: 65px;
      height: 52px;
      display: inline-block;
      text-align: center;
      line-height: 50px;
      background-color: #38f
    }
    .van-swipe-cell__right {
      color: #FFFFFF;
      font-size: 15px;
      width: 65px;
      height: 52px;
      display: inline-block;
      text-align: center;
      line-height: 50px;
      background-color: #F44;
    }
    .palette-button{
      position: fixed;
      right: 30px;
      bottom: 31px;
      z-index: 500;
    }
  }
</style>
